import axios from "axios";
import { ElMessage } from "element-plus";
import {getToken,delToken} from './token';
import {delStorage } from "@/utils/storage";
import { getStorage } from "@/utils/storage";
import { useRouter } from "vue-router";

const errorCode = {
    'default': '系统未知错误，请反馈给管理员',
}


const request = axios.create({
    baseURL: import.meta.env.VITE_BASE_API,
    timeout: 60000
})

// 请求拦截
request.interceptors.request.use(config => {
    // 传必参是加入对应参数
    if(config.hasOwnProperty('data')){
        const userInfo = getStorage('userInfo');
        if(userInfo){
            config.data.shop_id = userInfo.shop_id.toString();
        }
        config.data.token = getToken();
    }
    const TokenKey = 'Admin-Token';
    config.headers[TokenKey] = getToken();
    return config
})

// 响应拦截
request.interceptors.response.use(response => {
    const res = response.data;
    const msg = res.msg || '未知错误';
    const code = res.code;
    if(code == 200) {
        return response.data
    }
    switch (code) {
        case 423:
            delToken();
            delStorage("menu");
            ElMessage.error('登录状态已过期，请重新登录');
            return Promise.reject(new Error(res.message || 'Error'))
        default:
            ElMessage.error(msg);
            return Promise.reject(new Error(msg || 'Error'))
    }
    
},(error) => {
    ElMessage.error("网络错误");
    return Promise.reject(error)

})

export default request